package com.example.springboottest.example.thread;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * condition条件就是信号量，有等待就需要被唤醒，如果不唤醒永远等到下去,除非设置了超时时间
 */
public class ConditionMain {
    public static void main(String[] args) {
        Lock lock = new ReentrantLock();
        Condition condition = lock.newCondition();
        new Thread(new ConditionWait(lock, condition)).start();
        new Thread(new ConditionWait(lock, condition)).start();
        new Thread(new ConditionSignal(lock, condition)).start();
        new Thread(new ConditionSignal(lock, condition)).start();
    }
}

class ConditionWait implements Runnable {
    //锁
    private Lock lock;
    //同步队列
    private Condition condition;

    public ConditionWait(Lock lock, Condition condition) {
        this.lock = lock;
        this.condition = condition;
    }

    @Override
    public void run() {
        try {
            System.out.println("wait的锁地址" + lock);
            lock.lock();
            System.out.println("wait 开始阻塞");
            //阻塞当前线程
            condition.await();
//            Thread.sleep(10 * 1000);
            System.out.println("wait阻塞结束");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            System.out.println("wait释放锁");
            lock.unlock();
        }
    }
}

class ConditionSignal implements Runnable {
    private Lock lock;
    private Condition condition;

    public ConditionSignal(Lock lock, Condition condition) {
        this.lock = lock;
        this.condition = condition;
    }

    @Override
    public void run() {
        try {
            System.out.println("signal的锁地址" + lock);
            lock.lock();
            System.out.println("signal开始唤醒");
            condition.signal();
            System.out.println("signal唤醒结束");
        } catch (Exception e) {

        } finally {
            System.out.println("signal释放锁");
            lock.unlock();
        }
    }
}